const { query } = require('../config/mysqlConfig');
const { v4: uuidv4 } = require('uuid');
const User = require('../models/User');

// 生成唯一的6位群组邀请码
const generateGroupCode = () => {
  // 生成6位随机数字和字母的组合
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let code = '';
  for (let i = 0; i < 6; i++) {
    code += chars[Math.floor(Math.random() * chars.length)];
  }
  return code;
};

// 创建新群组
const createGroup = async (creatorId, name, description, groupAvatar = null) => {
  try {
    // 生成唯一群组邀请码
    let groupCode = generateGroupCode();
    let codeExists = true;

    // 确保生成的群组码是唯一的
    while (codeExists) {
      const existingGroups = await query(
        'SELECT id FROM `groups` WHERE group_code = ?',
        [groupCode]
      );

      if (existingGroups.length === 0) {
        codeExists = false;
      } else {
        groupCode = generateGroupCode();
      }
    }

    // 创建群组
    const result = await query(
      'INSERT INTO `groups` (name, description, creator_id, group_avatar, group_code) VALUES (?, ?, ?, ?, ?)',
      [name, description, creatorId, groupAvatar, groupCode]
    );

    const groupId = result.insertId;

    // 将创建者添加为管理员
    await query(
      'INSERT INTO group_members (group_id, user_id, role) VALUES (?, ?, ?)',
      [groupId, creatorId, 'admin']
    );

    // 获取新创建的群组信息
    const groups = await query('SELECT * FROM `groups` WHERE id = ?', [groupId]);

    if (groups.length > 0) {
      return {
        ...groups[0],
        members: [{ user_id: creatorId, role: 'admin', joined_at: new Date() }]
      };
    } else {
      throw new Error('创建群组失败');
    }
  } catch (error) {
    console.error('创建群组失败:', error);
    throw error;
  }
};

// 获取用户所在的所有群组
const getUserGroups = async (userId) => {
  try {
    const groups = await query(`
      SELECT g.*, gm.role, gm.joined_at
      FROM \`groups\` g
      JOIN group_members gm ON g.id = gm.group_id
      WHERE gm.user_id = ?
      ORDER BY g.name ASC
    `, [userId]);

    return groups;
  } catch (error) {
    console.error('获取用户群组失败:', error);
    throw error;
  }
};

// 获取群组信息
const getGroupInfo = async (groupId, userId) => {
  try {
    // 检查群组是否存在
    const groups = await query('SELECT * FROM `groups` WHERE id = ?', [groupId]);

    if (groups.length === 0) {
      throw new Error('群组不存在');
    }

    // 验证用户是否为群组成员或曾经是群组成员
    const membership = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    let isCurrentMember = membership.length > 0;
    
    if (!isCurrentMember) {
      // 检查是否曾经是群组成员（通过历史消息判断）
      const Message = require('../models/Message');
      const hasHistoryMessages = await Message.countDocuments({
        group_id: parseInt(groupId),
        target_type: 'group',
        sender: userId
      });

      if (hasHistoryMessages === 0) {
        throw new Error('您无权查看该群组信息');
      }

      console.log(`用户 ${userId} 曾经是群组 ${groupId} 的成员，允许查看基本信息`);
    }

    // 根据用户身份返回不同的信息
    if (isCurrentMember) {
      // 当前成员：返回完整信息
      const members = await query(`
        SELECT gm.user_id, gm.role, gm.joined_at
        FROM group_members gm
        WHERE gm.group_id = ?
      `, [groupId]);

      // 获取成员详细信息
      const memberIds = members.map(member => member.user_id);
      const userDetails = await User.find(
        { _id: { $in: memberIds } },
        'username avatar'
      );

      // 合并群组数据
      const groupWithMembers = {
        ...groups[0],
        members: members.map(member => {
          const userDetail = userDetails.find(u => u._id.toString() === member.user_id) || {};
          return {
            ...member,
            username: userDetail.username || '未知用户',
            avatar: userDetail.avatar || ''
          };
        }),
        isCurrentMember: true
      };

      return groupWithMembers;
    } else {
      // 曾经的成员：返回基本信息，标记为已退出
      const basicGroupInfo = {
        ...groups[0],
        members: [],
        isCurrentMember: false,
        status: 'left', // 标记用户已退出
        memberCount: 0,
        note: '您已退出该群组，只能查看历史消息'
      };

      return basicGroupInfo;
    }
  } catch (error) {
    console.error('获取群组信息失败:', error);
    throw error;
  }
};

// 通过群组邀请码查找群组
const findGroupByCode = async (groupCode) => {
  try {
    const groups = await query('SELECT * FROM `groups` WHERE group_code = ?', [groupCode]);

    if (groups.length === 0) {
      return null;
    }

    return groups[0];
  } catch (error) {
    console.error('查找群组失败:', error);
    throw error;
  }
};

// 发送邀请加入群组
const inviteToGroup = async (groupId, fromUserId, toUserId) => {
  try {
    // 检查邀请者是否为群成员
    const membership = await query(
      'SELECT role FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, fromUserId]
    );

    if (membership.length === 0) {
      throw new Error('您不是该群组的成员，无法发送邀请');
    }

    // 检查被邀请人是否已经是群成员
    const existingMember = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, toUserId]
    );

    if (existingMember.length > 0) {
      throw new Error('该用户已经是群组成员');
    }

    // 检查是否已经发送过邀请且未处理
    const existingInvitation = await query(
      `SELECT * FROM group_invitations
       WHERE group_id = ? AND from_user_id = ? AND to_user_id = ? AND status = 'pending'`,
      [groupId, fromUserId, toUserId]
    );

    if (existingInvitation.length > 0) {
      throw new Error('已经向该用户发送过邀请，等待回应中');
    }

    // 创建新邀请
    await query(
      `INSERT INTO group_invitations (group_id, from_user_id, to_user_id, status)
       VALUES (?, ?, ?, 'pending')`,
      [groupId, fromUserId, toUserId]
    );

    return { success: true, message: '群组邀请已发送' };
  } catch (error) {
    console.error('发送群组邀请失败:', error);
    throw error;
  }
};

// 获取用户的待处理群组邀请
const getPendingGroupInvitations = async (userId) => {
  try {
    const invitations = await query(`
      SELECT gi.*, g.name, g.description, g.group_avatar, g.id as group_id
      FROM group_invitations gi
      JOIN \`groups\` g ON gi.group_id = g.id
      WHERE gi.to_user_id = ? AND gi.status = 'pending'
    `, [userId]);

    // 获取邀请人信息
    const inviterIds = invitations.map(inv => inv.from_user_id);
    const inviters = await User.find(
      { _id: { $in: inviterIds } },
      'username avatar'
    );

    // 合并数据
    return invitations.map(invitation => {
      const inviter = inviters.find(u => u._id.toString() === invitation.from_user_id) || {};
      return {
        id: invitation.id,
        created_at: invitation.created_at,
        group: {
          id: invitation.group_id,
          name: invitation.name,
          description: invitation.description,
          group_avatar: invitation.group_avatar
        },
        inviter: {
          _id: invitation.from_user_id,
          username: inviter.username || '未知用户',
          avatar: inviter.avatar || ''
        }
      };
    });
  } catch (error) {
    console.error('获取群组邀请失败:', error);
    throw error;
  }
};

// 响应群组邀请
const respondToGroupInvitation = async (invitationId, userId, action) => {
  try {
    // 查询邀请详情
    const invitations = await query(
      `SELECT * FROM group_invitations WHERE id = ? AND to_user_id = ? AND status = 'pending'`,
      [invitationId, userId]
    );

    if (invitations.length === 0) {
      throw new Error('邀请不存在或已处理');
    }

    const invitation = invitations[0];

    // 更新邀请状态
    await query(
      'UPDATE group_invitations SET status = ? WHERE id = ?',
      [action, invitationId]
    );

    // 如果接受邀请，添加为群组成员
    if (action === 'accepted') {
      // 检查是否已经是成员
      const existingMember = await query(
        'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
        [invitation.group_id, userId]
      );

      if (existingMember.length === 0) {
        await query(
          'INSERT INTO group_members (group_id, user_id, role) VALUES (?, ?, ?)',
          [invitation.group_id, userId, 'member']
        );
      }
    }

    return {
      success: true,
      message: `群组邀请已${action === 'accepted' ? '接受' : '拒绝'}`,
      groupId: invitation.group_id
    };
  } catch (error) {
    console.error('响应群组邀请失败:', error);
    throw error;
  }
};

// 申请加入群组
const requestJoinGroup = async (groupId, userId) => {
  try {
    // 检查群组是否存在
    const groups = await query('SELECT * FROM `groups` WHERE id = ?', [groupId]);

    if (groups.length === 0) {
      throw new Error('群组不存在');
    }

    // 检查是否已经是成员
    const existingMember = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    if (existingMember.length > 0) {
      throw new Error('您已经是该群组的成员');
    }

    // 检查是否已经申请过且未处理
    const existingRequest = await query(
      `SELECT * FROM group_join_requests
       WHERE group_id = ? AND user_id = ? AND status = 'pending'`,
      [groupId, userId]
    );

    if (existingRequest.length > 0) {
      throw new Error('您已经发送过加入请求，等待回应中');
    }

    // 创建新请求
    await query(
      `INSERT INTO group_join_requests (group_id, user_id, status)
       VALUES (?, ?, 'pending')`,
      [groupId, userId]
    );

    return { success: true, message: '加入群组请求已发送' };
  } catch (error) {
    console.error('申请加入群组失败:', error);
    throw error;
  }
};

// 获取群组的待处理加入请求
const getPendingJoinRequests = async (groupId, adminUserId) => {
  try {
    // 验证用户是否是群管理员
    const membership = await query(
      `SELECT * FROM group_members
       WHERE group_id = ? AND user_id = ? AND role = 'admin'`,
      [groupId, adminUserId]
    );

    if (membership.length === 0) {
      throw new Error('您不是该群组的管理员');
    }

    const requests = await query(`
      SELECT * FROM group_join_requests
      WHERE group_id = ? AND status = 'pending'
    `, [groupId]);

    // 获取申请人信息
    const requesterIds = requests.map(req => req.user_id);
    const requesters = await User.find(
      { _id: { $in: requesterIds } },
      'username email avatar'
    );

    // 合并数据
    return requests.map(request => {
      const requester = requesters.find(u => u._id.toString() === request.user_id) || {};
      return {
        ...request,
        username: requester.username || '未知用户',
        email: requester.email || '',
        avatar: requester.avatar || ''
      };
    });
  } catch (error) {
    console.error('获取加入请求失败:', error);
    throw error;
  }
};

// 响应加入群组请求
const respondToJoinRequest = async (requestId, adminUserId, action) => {
  try {
    // 查询请求详情
    const requests = await query(
      `SELECT * FROM group_join_requests WHERE id = ? AND status = 'pending'`,
      [requestId]
    );

    if (requests.length === 0) {
      throw new Error('请求不存在或已处理');
    }

    const request = requests[0];

    // 验证用户是否是群管理员
    const membership = await query(
      `SELECT * FROM group_members
       WHERE group_id = ? AND user_id = ? AND role = 'admin'`,
      [request.group_id, adminUserId]
    );

    if (membership.length === 0) {
      throw new Error('您不是该群组的管理员');
    }

    // 更新请求状态
    await query(
      'UPDATE group_join_requests SET status = ? WHERE id = ?',
      [action, requestId]
    );

    // 如果接受请求，添加为群组成员
    if (action === 'accepted') {
      // 检查是否已经是成员
      const existingMember = await query(
        'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
        [request.group_id, request.user_id]
      );

      if (existingMember.length === 0) {
        await query(
          'INSERT INTO group_members (group_id, user_id, role) VALUES (?, ?, ?)',
          [request.group_id, request.user_id, 'member']
        );
      }
    }

    return {
      success: true,
      message: `加入请求已${action === 'accepted' ? '接受' : '拒绝'}`,
      userId: request.user_id
    };
  } catch (error) {
    console.error('响应加入请求失败:', error);
    throw error;
  }
};

// 离开群组
const leaveGroup = async (groupId, userId) => {
  try {
    // 检查用户是否是群成员
    const membership = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    if (membership.length === 0) {
      throw new Error('您不是该群组的成员');
    }

    // 检查群组创建者
    const group = await query('SELECT creator_id FROM `groups` WHERE id = ?', [groupId]);

    // 如果是创建者，验证是否是群组中唯一的管理员
    if (group[0].creator_id === userId) {
      // 查找其他管理员
      const admins = await query(
        `SELECT * FROM group_members
         WHERE group_id = ? AND role = 'admin' AND user_id != ?`,
        [groupId, userId]
      );

      if (admins.length === 0) {
        // 查找其他成员，将第一个成员升级为管理员
        const members = await query(
          `SELECT * FROM group_members
           WHERE group_id = ? AND user_id != ?
           ORDER BY joined_at ASC LIMIT 1`,
          [groupId, userId]
        );

        if (members.length > 0) {
          await query(
            `UPDATE group_members SET role = 'admin' WHERE group_id = ? AND user_id = ?`,
            [groupId, members[0].user_id]
          );

          // 更新群组创建者
          await query(
            `UPDATE groups SET creator_id = ? WHERE id = ?`,
            [members[0].user_id, groupId]
          );
        } else {
          // 如果没有其他成员，删除群组
          await query('DELETE FROM groups WHERE id = ?', [groupId]);
          return { success: true, message: '您是唯一成员，群组已删除' };
        }
      } else {
        // 更新群组创建者为第一个管理员
        await query(
          `UPDATE groups SET creator_id = ? WHERE id = ?`,
          [admins[0].user_id, groupId]
        );
      }
    }

    // 从群组中移除成员
    await query(
      'DELETE FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    return { success: true, message: '您已离开群组' };
  } catch (error) {
    console.error('离开群组失败:', error);
    throw error;
  }
};

// 更新群组信息
const updateGroupInfo = async (groupId, adminUserId, updateData) => {
  try {
    // 验证用户是否是群管理员
    const membership = await query(
      `SELECT * FROM group_members
       WHERE group_id = ? AND user_id = ? AND role = 'admin'`,
      [groupId, adminUserId]
    );

    if (membership.length === 0) {
      throw new Error('您不是该群组的管理员');
    }

    const { name, description, group_avatar } = updateData;
    let updateFields = [];
    let updateValues = [];

    if (name) {
      updateFields.push('name = ?');
      updateValues.push(name);
    }

    if (description !== undefined) {
      updateFields.push('description = ?');
      updateValues.push(description);
    }

    if (group_avatar !== undefined) {
      updateFields.push('group_avatar = ?');
      updateValues.push(group_avatar);
    }

    if (updateFields.length === 0) {
      throw new Error('没有提供要更新的数据');
    }

    // 添加groupId到更新参数
    updateValues.push(groupId);

    // 执行更新
    await query(
      `UPDATE \`groups\` SET ${updateFields.join(', ')} WHERE id = ?`,
      updateValues
    );

    // 获取更新后的群组信息
    const groups = await query('SELECT * FROM `groups` WHERE id = ?', [groupId]);

    return groups[0];
  } catch (error) {
    console.error('更新群组信息失败:', error);
    throw error;
  }
};

// 管理群组成员（移除成员或更新角色）
const manageGroupMember = async (groupId, adminUserId, targetUserId, action, newRole) => {
  try {
    // 获取群组信息
    const groups = await query('SELECT creator_id, status FROM `groups` WHERE id = ?', [groupId]);

    if (groups.length === 0) {
      throw new Error('群组不存在');
    }

    if (groups[0].status === 'disbanded') {
      throw new Error('群组已解散，无法管理成员');
    }

    const isCreator = groups[0].creator_id === adminUserId;

    // 验证操作者是否有权限
    const adminMembership = await query(
      `SELECT role FROM group_members
       WHERE group_id = ? AND user_id = ?`,
      [groupId, adminUserId]
    );

    if (adminMembership.length === 0) {
      throw new Error('您不是该群组的成员');
    }

    const isAdmin = adminMembership[0].role === 'admin';

    // 只有创建者和管理员可以管理成员
    if (!isCreator && !isAdmin) {
      throw new Error('您没有权限管理群组成员');
    }

    // 验证目标用户是否是群成员
    const targetMembership = await query(
      'SELECT role FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, targetUserId]
    );

    if (targetMembership.length === 0) {
      throw new Error('目标用户不是该群组的成员');
    }

    const targetRole = targetMembership[0].role;

    // 检查是否尝试对创建者执行操作
    if (groups[0].creator_id === targetUserId && adminUserId !== targetUserId) {
      throw new Error('无法对群组创建者执行此操作');
    }

    // 防止管理员操作其他管理员（只有创建者可以）
    if (!isCreator && targetRole === 'admin' && adminUserId !== targetUserId) {
      throw new Error('只有群主可以管理其他管理员');
    }

    switch (action) {
      case 'remove':
        // 从群组中移除成员
        await query(
          'DELETE FROM group_members WHERE group_id = ? AND user_id = ?',
          [groupId, targetUserId]
        );
        return { success: true, message: '成员已从群组中移除' };

      case 'updateRole':
        if (!newRole || !['member', 'admin'].includes(newRole)) {
          throw new Error('无效的角色');
        }

        // 只有群主可以设置管理员
        if (newRole === 'admin' && !isCreator) {
          throw new Error('只有群主可以设置管理员');
        }

        // 更新成员角色
        await query(
          'UPDATE group_members SET role = ? WHERE group_id = ? AND user_id = ?',
          [newRole, groupId, targetUserId]
        );

        return {
          success: true,
          message: `成员角色已更新为 ${newRole === 'admin' ? '管理员' : '成员'}`
        };

      default:
        throw new Error('无效的操作');
    }
  } catch (error) {
    console.error('管理群组成员失败:', error);
    throw error;
  }
};

// 添加成员到群组
const addMemberToGroup = async (groupId, userId, role = 'member') => {
  try {
    // 检查群组是否存在
    const groups = await query('SELECT * FROM `groups` WHERE id = ?', [groupId]);

    if (groups.length === 0) {
      throw new Error('群组不存在');
    }

    // 检查是否已经是成员
    const existingMember = await query(
      'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    if (existingMember.length > 0) {
      return { success: true, message: '用户已经是群组成员' };
    }

    // 添加为成员
    await query(
      'INSERT INTO group_members (group_id, user_id, role) VALUES (?, ?, ?)',
      [groupId, userId, role]
    );

    return { success: true, message: '成员已添加到群组' };
  } catch (error) {
    console.error('添加群组成员失败:', error);
    throw error;
  }
};

// 移除群组成员
const removeMemberFromGroup = async (groupId, userId, currentUserId) => {
  try {
    // 检查群组是否存在
    const groups = await query('SELECT creator_id FROM `groups` WHERE id = ?', [groupId]);

    if (groups.length === 0) {
      throw new Error('群组不存在');
    }

    // 检查当前用户是否有权限移除成员
    // 只有创建者和管理员可以移除成员
    const currentUserRole = await query(
      'SELECT role FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, currentUserId]
    );

    if (currentUserRole.length === 0) {
      throw new Error('您不是该群组的成员');
    }

    const isCreator = groups[0].creator_id === currentUserId;
    const isAdmin = currentUserRole[0].role === 'admin';

    if (!isCreator && !isAdmin && currentUserId !== userId) {
      throw new Error('您没有权限移除其他成员');
    }

    // 禁止移除创建者
    if (userId === groups[0].creator_id && currentUserId !== userId) {
      throw new Error('不能移除群组创建者');
    }

    // 移除成员
    await query(
      'DELETE FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    return { success: true, message: '成员已从群组移除' };
  } catch (error) {
    console.error('移除群组成员失败:', error);
    throw error;
  }
};

// 解散群组（软删除）
const deleteGroup = async (groupId, userId) => {
  try {
    // 检查群组是否存在且未解散
    const groups = await query('SELECT creator_id, status FROM `groups` WHERE id = ?', [groupId]);

    if (groups.length === 0) {
      throw new Error('群组不存在');
    }

    if (groups[0].status === 'disbanded') {
      throw new Error('群组已解散');
    }

    // 验证用户是否是群创建者
    if (groups[0].creator_id !== userId) {
      throw new Error('只有群组创建者才能解散群组');
    }

    // 开始事务
    const connection = await require('../config/mysqlConfig').pool.getConnection();
    await connection.beginTransaction();

    try {
      // 标记群组为已解散
      await connection.query(
        'UPDATE `groups` SET status = "disbanded", disbanded_at = NOW(), disbanded_by = ? WHERE id = ?',
        [userId, groupId]
      );

      // 删除待处理的群组邀请
      await connection.query('DELETE FROM group_invitations WHERE group_id = ? AND status = "pending"', [groupId]);

      // 删除待处理的加入请求
      await connection.query('DELETE FROM group_join_requests WHERE group_id = ? AND status = "pending"', [groupId]);

      // 提交事务
      await connection.commit();

      return { success: true, message: '群组已解散' };
    } catch (err) {
      // 回滚事务
      await connection.rollback();
      throw err;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('解散群组失败:', error);
    throw error;
  }
};

// 获取用户在群组中的权限
const getUserGroupPermissions = async (groupId, userId) => {
  try {
    // 获取群组信息
    const groups = await query('SELECT creator_id, status FROM `groups` WHERE id = ?', [groupId]);

    if (groups.length === 0) {
      throw new Error('群组不存在');
    }

    const isCreator = groups[0].creator_id === userId;

    // 获取用户在群组中的角色
    const membership = await query(
      'SELECT role FROM group_members WHERE group_id = ? AND user_id = ?',
      [groupId, userId]
    );

    if (membership.length === 0) {
      return {
        isMember: false,
        isCreator: false,
        isAdmin: false,
        canManageMembers: false,
        canManageGroup: false
      };
    }

    const isAdmin = membership[0].role === 'admin';

    return {
      isMember: true,
      isCreator,
      isAdmin,
      canManageMembers: isCreator || isAdmin,
      canManageGroup: isCreator || isAdmin,
      role: isCreator ? 'creator' : membership[0].role
    };
  } catch (error) {
    console.error('获取用户群组权限失败:', error);
    throw error;
  }
};

module.exports = {
  generateGroupCode,
  createGroup,
  getUserGroups,
  getGroupInfo,
  findGroupByCode,
  inviteToGroup,
  getPendingGroupInvitations,
  respondToGroupInvitation,
  requestJoinGroup,
  getPendingJoinRequests,
  respondToJoinRequest,
  leaveGroup,
  updateGroupInfo,
  manageGroupMember,
  addMemberToGroup,
  removeMemberFromGroup,
  deleteGroup,
  getUserGroupPermissions
};